(function () {
	"use strict";

	app.controller('adhibitionAppCtrl', ['$scope','$interval', 'webSocket','httpLoad', '$rootScope', '$modal', '$state', '$timeout','$location','$anchorScroll',
		function ($scope,$interval,webSocket,httpLoad, $rootScope, $modal, $state, $timeout,$location,$anchorScroll) {
			$rootScope.moduleTitle = '应用服务 > 应用实例';//定义当前页

			//websocket异步操作
			webSocket.onmessage({
				message:function (data) {
					if($rootScope.currentUrl=='app.adhibition.apply'&&(data.operate=='application/imageDeploy')){
						$scope.getData();
					}else if($rootScope.currentUrl=='app.adhibition.apply'&&(data.operate=='application/layoutDeploy')){
						$scope.getData();
					}
				}
			});

		  $scope.isListView = true;
			$scope.param = {
				page:1,
				rows: 10
			};
			$scope.options = {
				apply:{
					theme:'',
 		 			unit:''
				},
				cpu:{
					showTitle:true,
					theme:'CPU',
					colorMap:{
						'已使用':'#00D7AF',
						'未使用':'#5296EB',

					},
					dataMap:{
						requestCpu:'已使用',
						notRequestCpu:'未使用',

					},
					realValue:''
				},
				app:{
					showTitle:true,
					theme:'应用',
					colorMap:{
						'已部署':'#00D7AF',
						'未部署':'#5296EB',
						'部署中':'#FF837E',

					},
					dataMap:{
						deploy:'已部署',
						notDeploy:'未部署',
						executeDeploy:'部署中',
					},
					realValue:''

				},
				memory:{
					showTitle:true,
					theme:'内存',
					colorMap:{
						'已使用':'#00D7AF',
						'未使用':'#5296EB',
					},
					dataMap:{
						requestMemory:'已使用',
						notRequestMemory:'未使用',
					},
					realValue:''
				}


			}
			//饼状图
			httpLoad.loadData({
					url: '/diagram/data',
					method: 'GET',
				//	noParam:true,
					success: function(data){
						if(data.success) {
							$scope.isDataLoad = true;
							$scope.dashboradData = data.data;



						}
					}
				});
				$scope.paramObj = {
					 resourceName:'',
					 namespace:''
				 };
				$scope.monitorDeta ={
					keys: [],
					values: [
					{
					data: [	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
					name: "Memory",
					},
					{
						data: [	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
					name: "Network Send",
					},
					{
						data: [	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
					name: "Network Received",
					},
					{
						data: [	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
					name: "CPU",
					}
				],
				} ;
				var setXDate = function(keys){
					$scope.isSetx = false;
					var data = {
						"keys": keys,
						values: $scope.monitorDeta.values
					};
					$scope.countData.forEach(function (item) {
						if(item.replicas==0){
						item.performance= data;
					}});
				};
			 //监控
			 $scope.monitored = function (item) {
				 var paramObj = {
						 type:'pod',
						 appId:item.id,

				 };
					httpLoad.loadData({
							url: '/openshift/monitor/app/monitor',
							method: 'GET',
							data:paramObj,
							//noParam:true,
							success: function(data){
								if(data.success) {
									if(data.data.keys){
										if($scope.isSetx) setXDate(data.data.keys)
										item.performance = data.data;
									}
							}else if($scope.timeInterval){
									$interval.cancel($scope.timeInterval);
									$scope.timeInterval = '';
							}
							}
						});

			 }
			 $scope.timeInterval = $interval(function () {
				 $scope.countData.forEach(function(item){
					 	if(item.replicas==0){

						}else{
							$scope.monitored(item);
						}
					})
			}, 120*1000);
			//获取云主机列表
			$scope.getData = function (page) {
				$scope.isSetx = true;
				$scope.param.page = page || $scope.param.page;
				httpLoad.loadData({
					url: '/application/list',
					method: 'POST',
					data: $scope.param,
					noParam: true,
					success: function (data) {
						if (data.success) {
							$scope.countData = data.data.rows;
							$scope.totalCount = data.data.total;
							if(!$scope.totalCount){
								$scope.isImageData = true;
								} else {
									$scope.isImageData = false;
							}
							$scope.countData.forEach(function(item){
								item.performance = $scope.monitorDeta
								if(item.replicas!=0){
									$scope.monitored(item);
								}
							})

						}else if($scope.timeInterval){
							$interval.cancel($scope.timeInterval);
							$scope.timeInterval = '';
						}
					}
				});
			};

			$scope.getData(1);
			$scope.$on("$destroy", function(event) {
				$interval.cancel($scope.timeInterval);
			});
			//详情
			$scope.detail = function(id,clusterId){

				$state.go('app.adhibition.applytiondetail', {id: id,clusterId:clusterId})

			}
			//搜索
			$scope.search = function () {
				//对参数进行处理，去除空参数
				var toObjFormat = function (obj) {
					for (var a in obj) {
						if (obj[a] == "") delete obj[a];
					}
					return obj;
				}
				var params = [];
				var param1 = toObjFormat({
					"a.name": $scope.searchByName
				});
				if (angular.toJson(param1).length > 2) params.push({param: param1, sign: 'LK'});

				$scope.param = {
					page: 1,
					rows: 10,
					params: angular.toJson(params)
				}
				$scope.getData();
			}
			//重置搜索条件
			$scope.reset = function () {
				var obj = ['name'];
				angular.forEach(obj, function (data) {
					$scope[data] = '';
				})
			}
			$scope.goBack = function(){
						 $scope.isActive = false;
						 $timeout(function() {
								 $scope.showHistory = false;
						 }, 200);
				 };
				 $scope.gohistory = function($event){
					 //历史记录
						$event.stopPropagation();
					 $scope.isActive = true ;
					 $scope.showHistory = true;
		};
			//全选
			$scope.operation = {};
			$scope.operation.isBatch1 = true;$scope.operation.isALl = false;
			$scope.selectALl = function(){
				$scope.operation.isBatch1 = !$scope.operation.isALl;
						$scope.countData.forEach(function(item){
							item.select = $scope.operation.isALl;
						});
			}
			$scope.choose = function(){
				var a = 0,b=0;
				$scope.countData.forEach(function(item){
					if(item.select==true) a++;
					else b=1;
				});
				if(a>=1) $scope.operation.isBatch1 = false;
				else $scope.operation.isBatch1 = true;
				if(b==1) $scope.operation.isALl = false;
				else $scope.operation.isALl = true;
			};
			//返回
			$scope.goAction = function (flag, id, $event) {
				switch (flag / 1) {
					case 1:
					//新增

					var modalInstance = $modal.open({
						templateUrl : '/statics/tpl/adhibition/apply/add.html',
						controller : 'addApplyModalCtrl',// 初始化模态范围
						//size : sm, //大小配置
						backdrop: 'static',
						resolve : {
							id : function(){
								return id;
							},
						}
				});
				modalInstance.result.then(function(){
						$scope.getData(1);
				},function(){});

						break;
					case 2:
					//编辑
							var modalInstance = $modal.open({
									templateUrl : '/statics/tpl/adhibition/apply/add.html',
								controller : 'addApplyModalCtrl',
								backdrop: 'static',
								resolve : {
									id : function(){
										return id;
									},

								}
							});
							modalInstance.result.then(function(){
								$scope.getData(1);
							},function(){});

						break;
					case 3:
						//删除
								if($event) $event.stopPropagation();
								var ids=[];
								ids.push(id);
								var modalInstance = $modal.open({
									templateUrl : '/statics/tpl/adhibition/apply/remove.html',
									controller : 'removeApplyModalCtrl',
										backdrop: 'static',
									resolve : {
										id : function(){
											return ids;
										},

									}
								});
								modalInstance.result.then(function(){
									$scope.getData(1);
									$scope.isCheck = false;
								},function(){});

						break;
					case 4:
					//部署
						$scope.$on("$destroy", function(event) {
							$interval.cancel($scope.timeInterval);
						});
					$state.go('app.adhibition.applytiondeploy', {id: id})
						break;
				}
			};

			$scope.deteleAll = function ($event) {
				var ids = [];
				for(var i=0;i<$scope.countData.length;i++){
					var item = $scope.countData[i]
					if(item.select){
						ids.push(item.id);
					}
				}
				var modalInstance = $modal.open({
					templateUrl : '/statics/tpl/adhibition/apply/remove.html',
					controller : 'removeApplyModalCtrl',
						backdrop: 'static',
					resolve : {
						id : function(){
							return ids;
						},

					}
				});
				modalInstance.result.then(function(){
					$scope.getData(1);
					$scope.operation.isALl = false;
					$scope.operation.isBatch1 = true;
					angular.forEach($scope.countData, function (data, index) {
						data.select = false;
				})
				},function(){});
			};
		}
	]);
	//新增ctrl
	 angular.module('app').controller('addApplyModalCtrl',['$scope','$modalInstance','LANGUAGE','httpLoad','id',
			 function($scope,$modalInstance,LANGUAGE,httpLoad,id){ //依赖于modalInstance
				 var editObj = ['name', 'remark'];
   	 		$scope.modalName = '应用创建';
					var url = '/application/create';
					 $scope.addData = {};
					 //如果为编辑，进行赋值
	        if (id) {
	                url = '/application/modify';
	                $scope.modalName = '应用编辑';
	                httpLoad.loadData({
	                    url: '/application/detail',
	                    method: 'GET',
	                    data: {id: id},
	                    success: function (data) {
	                        if (data.success) {
	                            var data = data.data;
	                            for (var a in editObj) {
	                                var attr = editObj[a];
	                                $scope.addData[attr] = data[attr];
	                            }

	                        }
	                    }
	                });
	            }
					$scope.ok = function () {
							 var param = {};
							 for (var a in editObj) {
									 var attr = editObj[a];
									 param[attr] = $scope.addData[attr];
							 }
							 if (id) param.id = id;
							 httpLoad.loadData({
									 url:url,
									 method:'POST',
									 data: param,
									 success:function(data){
											 if(data.success){
													$scope.pop(data.message);
													 $modalInstance.close();
											 }
									 }
							 });
					 }

					 $scope.cancel = function(){
							$modalInstance.dismiss('cancel');
					 };
			 }]);

	//删除ctrl
	angular.module('app').controller('removeApplyModalCtrl',['$scope','$modalInstance','httpLoad','LANGUAGE','id',
		function($scope,$modalInstance,httpLoad,LANGUAGE,id){ //依赖于modalInstance
			$scope.messageApply = '本应用包含的部署、服务和运行实例都将彻底删除，确认删除？';

			$scope.ok = function(){
				$scope.isCheck = true;
				httpLoad.loadData({
					url:'/application/remove',
					method:'POST',
					data: {ids:id},
					success:function(data){
						if(data.success){
							//console.log(removeData);
							$scope.pop(data.message);
							$modalInstance.close();
						}else{
									$modalInstance.dismiss('cancel');
									$scope.operation.isBatch1 = false;
						}
					}
				});
			};
			$scope.cancel = function(){
			$modalInstance.dismiss('cancel');
			$scope.operation.isBatch1 = true;
			}
		}]);
		//导入
		angular.module('app').controller('gridinModalCtrl',['$scope','$modalInstance','httpLoad','LANGUAGE',
			function($scope,$modalInstance,httpLoad,LANGUAGE){ //依赖于modalInstance

				$scope.ok = function(){
					httpLoad.loadData({
						url:'/user/remove',
						method:'POST',
						data: removeData,
						success:function(data){
							if(data.success){
								//console.log(removeData);
								$scope.pop(data.message);
								$modalInstance.close();
							}
						}
					});
				};
				$scope.cancel = function(){
			$modalInstance.dismiss('cancel');
				}
			}]);
			app.controller('applyhistoryModalCtrl', ['$rootScope', '$scope','$state','httpLoad','$stateParams',function($rootScope, $scope,$state,httpLoad,$stateParams) {
				$rootScope.link = '/statics/css/alarm.css';//引入页面样式
			  $scope.param = {
			  		page:1,
			 	        rows: 10,
			 	        params:angular.toJson([{"param":{"object":"application/operation"},"sign":"LK"}])
			 	    };
			    $scope.getHistory = function (page) {
			      var id = $stateParams.id;
			      httpLoad.loadData({
			        url: '/app/log/list',
			          method:'POST',
			          data: $scope.param,
			          noParam:true,
			          success:function(data){
			              if(data.success&&data.data){
			                  $scope.userList = data.data.rows;
			                  $scope.totalCount = data.data.total;
			                  if(data.data.rows==[]){
			                      $scope.pop("返回数据为空");
			                  }
			                  if (data.data.rows.length == 0) {
			                    $scope.isImageData = true;
			                    return;
			                  } else $scope.isImageData = false;
			              }

			          }
			      });
			  }
		$scope.getHistory(1)
			}]);

})();
